/*
 * $RCSfile: DemonAction.java,v $
 * $Revision: 1.1 $
 * $Date: 2014-03-25 $
 *
 * Copyright (C) 2005 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.demon.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.demon.BeanFactory;
import com.skin.demon.Parameters;
import com.skin.demon.ServiceInvocation;
import com.skin.j2ee.action.BaseAction;
import com.skin.j2ee.annotation.UrlPattern;
import com.skin.util.StringUtil;

/**
 * <p>Title: DemonAction</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class DemonAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(AgentAction.class);

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webeye/demon.html")
    public void index() throws IOException, ServletException {
        String method = this.getTrimString("method");
        String content = this.getInvokeScript(method);

        if(content == null) {
            StringBuilder buffer = new StringBuilder();
            buffer.append("// 请在此处输入要调用的类和方法名, 请使用JS语法.\r\n");
            buffer.append("// 例如: test.UserManager.getUserListByStatus(\"NORMAL\", 2, 100);\r\n");
            buffer.append("\r\n\r\n\r\n\r\n\r\n");
            content = buffer.toString();
        }

        this.setAttribute("content", content);
        this.forward("/template/webeye/demon.jsp");
    }

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webeye/demon/invoke.html")
    public void invoke() throws IOException, ServletException {
        logger.info("invoke: {}", this.request.getParameter("serviceName"));

        this.response.setContentType("text/plain; charset=utf-8");
        PrintWriter out = this.response.getWriter();
        Parameters parameters = this.getParameters(this.request);
        BeanFactory beanFactory = this.getBeanFactory();
        ServiceInvocation invocation = new ServiceInvocation(beanFactory, out);

        try {
            invocation.execute(parameters);
        }
        catch(Exception e) {
            e.printStackTrace(out);
        }
        out.flush();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        DemonAction da = new DemonAction();
        String text = "com.skin.eye.ClassScanner.add(java.util.Map, java.lang.String, java.lang.String, boolean)";
        String code = da.getInvokeScript(text);
        System.out.println(code);
    }

    /**
     * @param message
     */
    public static void test1(String message) {
        System.out.println(message);
    }

    /**
     * @param text
     * @return String
     */
    private String getInvokeScript(String text) {
        if(StringUtil.isBlank(text)) {
            return null;
        }

        int i = text.indexOf('(', 0);

        if(i < 0) {
            return null;
        }

        int j = text.lastIndexOf('.', i - 1);

        if(j < 0) {
            return null;
        }

        String className = text.substring(0, j).trim();
        String methodName = text.substring(j + 1, i);
        String args = text.substring(i + 1).trim();
        StringBuilder buffer = new StringBuilder();
        buffer.append("// 请在此处输入要调用的类和方法名, 请使用JS语法.\r\n");
        buffer.append("// ");

        if(args.endsWith(";")) {
            args = args.substring(0,  args.length() - 1);
        }

        if(args.endsWith(")")) {
            args = args.substring(0,  args.length() - 1);
        }

        String[] parameterTypeNames = StringUtil.split(args, ",", true, true);

        try {
            Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];

            for(i = 0; i < parameterTypeNames.length; i++) {
                String typeName = parameterTypeNames[i];
                parameterTypes[i] = ServiceInvocation.getClass(typeName);
            }

            Class<?> type = ServiceInvocation.getClass(className);
            Method method = type.getDeclaredMethod(methodName, parameterTypes);
            buffer.append("junit@");
            buffer.append(type.getName());
            buffer.append(".");
            buffer.append(method.getName());
            buffer.append("(");

            if(parameterTypeNames.length > 0) {
                for(String typeName : parameterTypeNames) {
                    buffer.append(typeName);
                    buffer.append(", ");
                }
                buffer.delete(buffer.length() - 2, buffer.length());
            }
            buffer.append(")\r\n");
            buffer.append("\r\n\r\n\r\n\r\n\r\n");
        }
        catch (Exception e) {
        }
        return buffer.toString();
    }

    /**
     * @param request
     * @return Parameters
     */
    private Parameters getParameters(HttpServletRequest request) {
        Parameters parameters = new Parameters();
        java.util.Enumeration<?> enums = request.getParameterNames();

        while(enums.hasMoreElements()) {
            String name = (String)(enums.nextElement());
            String value = request.getParameter(name);

            if(value != null) {
                parameters.setValue(name, value);
            }
        }
        return parameters;
    }

    /**
     * @return BeanFactory
     */
    private BeanFactory getBeanFactory() {
        return null;
    }
}
